package com.irdstudio.efp.esb.api.rest.sx;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.constant.CertTypeConstant;
import com.irdstudio.basic.framework.core.constant.CurrencyConstant;
import com.irdstudio.basic.framework.core.constant.DateFormatConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.threadpool.ApplicationThreadPool2;
import com.irdstudio.basic.framework.core.util.*;
import com.irdstudio.efp.basic.framework.mq.client.producer.MQProducerMessageClient;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.common.YedConstantSet;
import com.irdstudio.efp.console.common.YedEnums;
import com.irdstudio.efp.console.service.facade.PrdInfoService;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.cus.service.facade.CompanyWhiteListRecordService;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.cus.service.vo.KafkaNoticeHeader;
import com.irdstudio.efp.esb.api.bean.sx.ReqYEDCreditBean;
import com.irdstudio.efp.esb.api.bean.sx.RespCreditBean;
import com.irdstudio.efp.esb.api.bean.sx.RespYedCreditBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.SDicServerConstant;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.api.util.SDicMappingServer;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.InstitutionEnums;
import com.irdstudio.efp.esb.common.constant.MsLoanConstant;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.esb.service.bo.req.sx.QryRptsInfArryBean;
import com.irdstudio.efp.esb.service.bo.req.sx.YedCreditRiskApproveReq;
import com.irdstudio.efp.esb.service.bo.resp.sx.YedCreditRiskApproveResp;
import com.irdstudio.efp.esb.service.facade.esb.EsbService;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.nls.common.constant.PrdAdaptedSoltEnums;
import com.irdstudio.efp.nls.common.constant.QueueTaskEnums;
import com.irdstudio.efp.nls.common.util.KafkaUtil;
import com.irdstudio.efp.nls.service.common.rules.ValidatePrdRule;
import com.irdstudio.efp.nls.service.facade.NlsStageInfoService;
import com.irdstudio.efp.nls.service.facade.queue.NlsProcessBizService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoExdService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.facade.yed.YedSqsSignatureService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import com.irdstudio.efp.nls.service.vo.NlsCreditInfoNoticeVO;
import com.irdstudio.efp.nls.service.vo.NlsStageInfoVO;
import com.irdstudio.efp.nls.service.vo.SignatureRecordVO;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoExdVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 优e贷进件申请
 *
 * @author dengqiwen
 * @version 1.0
 * @since 2020年07月24日
 */
@RestController
@RequestMapping("/esb")
public class NlsCreditYEDController implements EsbController {
    private static Logger logger = LoggerFactory.getLogger(NlsCreditYEDController.class);

    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;
    @Autowired
    @Qualifier("nlsProcessBizService")
    private NlsProcessBizService nlsProcessBizService;
    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;
    @Autowired
    @Qualifier("prdInfoService")
    private PrdInfoService prdInfoService;
    @Autowired
    @Qualifier("producerService")
    private MQProducerMessageClient producerService;
    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    @Autowired
    @Qualifier("applicationThreadPool")
    private ApplicationThreadPool2 threadPool;

    @Autowired
    @Qualifier("yedSqsSignatureService")
    private YedSqsSignatureService yedSqsSignatureService;

    @Autowired
    @Qualifier("companyWhiteListRecordService")
    private CompanyWhiteListRecordService companyWhiteListRecordService;

    @Autowired
    @Qualifier("nlsStageInfoService")
    private NlsStageInfoService nlsStageInfoService;

    @Autowired
    @Qualifier("nlsCreditInfoExdService")
    private NlsCreditInfoExdService nlsCreditInfoExdService;

    // kafka发送的主题topic
    @Value("${risk.kafkaToptic}")
    private String kafkaToptic;

    // kafka主机IP地址
    @Value("${risk.kafkaServers}")
    private String kafkaServers;

    // 单位转换
    private final int oneHundred_100 = 100;
    private static final String MYD_TRN_DAY_30 = "30";
    private static final String ZXD_TRN_DAY_7 = "7";

    /**
     * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
     *
     * @param request 请求对象集合
     * @return
     * @author huangwb
     * @version 1.0
     * @since 2019年1月20日 下午1:28:08
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("校验 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request 请求对象集合
     * @return
     * @author huangwb
     * @version 1.0
     * @since 2019年1月20日 下午1:31:14
     */
    @ModelAttribute("reqYEDCreditBean")
    public ReqYEDCreditBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("校验 ESB请求体对象！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqYEDCreditBean.class);
    }

    /**
     * 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息<br>
     * 2.调用对应的中台服务<br>
     * 3.增加调用队列任务表信息<br>
     * 此处为统一的进件交易，先暂时不按照产品代码进行划分，后续根据差异化需求决定是否拆分；
     *
     * @param esbReqServiceBean ESB请求对象
     * @param br1
     * @param reqCreditBean     ESB请求体的对象
     * @param br2
     * @param exception         切面的异常信息
     * @return
     * @throws Exception
     * @author huangwb
     * @version 1.0
     * @since 2019年1月20日 下午2:20:51
     */
    @PostMapping("/SERVICE_30220001_23")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqYEDCreditBean") ReqYEDCreditBean reqCreditBean, BindingResult br2, Exception exception) throws Exception {
        String applSeq = reqCreditBean.getCrAppSrlNo();
        String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
        // 设置系统头对象
        setSysHeadFieldThreadLocal(esbReqServiceBean);
        logger.info("优e贷授信申请交易开始----------申请流水号：" + applSeq + "------------全局流水号" + glblSrlNo);
        try {
            // 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息
            if (Objects.nonNull(exception)) {
                throw exception;
            }
            // 2.获取业务逻辑字段
            String cusName = reqCreditBean.getCustNm();
            String certType = StringUtil.isNullorBank(reqCreditBean.getIdentTp()) ? CertTypeConstant.CODE_10100 : SDicMappingServer.getLocalSysDicVal(SDicServerConstant.CERT_TYPE, reqCreditBean.getIdentTp());
            String certNo = reqCreditBean.getIdentNo();
            String mobile = reqCreditBean.getMblNo();
            String prdCde = reqCreditBean.getPdCd();
            String chanNo = reqCreditBean.getUsedChanNo();
            //2.校验是否重复授信，根据证件号，产品编号查询授信申请表（nls_credit_info），审批状态为处理中，拒绝授信申请，提示已经授信申请过。
            NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
            nlsCreditInfoVO.setCertType(certType);
            nlsCreditInfoVO.setCertCode(certNo);
            nlsCreditInfoVO.setPrdCode(YedEnums.PrdIdEnum.YED.getValue());
            List<NlsCreditInfoVO> nlsCreditInfoVos = nlsCreditInfoService.countPeopelHasCredits(nlsCreditInfoVO);
            if (nlsCreditInfoVos != null && nlsCreditInfoVos.size() > 0) {
                for (NlsCreditInfoVO pojo:nlsCreditInfoVos) {
                    if(BaseConstant.NLS_APPLY_STATE_01.equals(pojo.getApprvSts()) || MsLoanConstant.NlsApplyStateEnum.HANG.getVALUE().equals(pojo.getApprvSts())){
                        return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                                JSON.toJSONString(buildRespCreditBean(EsbBizEnums.YedRespCode.REJECT.getValue())),
                                EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                                EsbBizEnums.RetCodeEnum.KHXXJYBTG.getVALUE(),
                                "尊敬的客户，您在我行申请的优e贷仍在审批中。请待审批结束后再试，谢谢！");
                    }
                    //3.审批状态处理成功且授信额度在有效期内的，也提示已存在；处理成功且额度过期的，不提示。
                    if(pojo.getApprvSts().equals(BaseConstant.NLS_APPLY_STATE_02)){
                        //查询授信协议表-lmt_prd_cont,看授信额度是否在有效期内
                        LmtPrdContVO lmtPrdContVO = lmtPrdContService.qryLmtPrdContByLmtApplySeq(pojo.getLmtApplySeq());
                        // 当前日期
                        String currentDate = DateTool.getCurrentDate();
                        //额度到期日期
                        String expireDate = lmtPrdContVO.getExpireDate();
                        //判断如果额度到期日期>当前日期，则该笔授信还有效，所以拒绝当前授信
                        int i = TimeUtil.compareDates(expireDate, currentDate);
                        if(i>=0){
                            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                                    JSON.toJSONString(buildRespCreditBean(EsbBizEnums.YedRespCode.REJECT.getValue())),
                                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                                    EsbBizEnums.RetCodeEnum.KHXXJYBTG.getVALUE(),
                                    "尊敬的客户，您在我行已经存在优e贷有效授信额度，谢谢！");
                        }
                    }
                }
            }

            //判断全局流水号是否存在
            final NlsCreditInfoVO golbalSernoParam = new NlsCreditInfoVO();
            golbalSernoParam.setGlobalSerno(glblSrlNo);
            final List<NlsCreditInfoVO> nlsCreditInfoVOS = nlsCreditInfoService.selectByGlobalSerno(golbalSernoParam);
            if (nlsCreditInfoVOS != null && !nlsCreditInfoVOS.isEmpty()) {
                throw new BizException("已存在全局流水号为" + glblSrlNo + "的请求记录");
            }
            // 3.校验产品信息是否存在以及是否有效，查询产品表（prd_info）。如果不存在或者失效，则提示对应信息。
            PrdInfoVO vo = new PrdInfoVO();
            vo.setPrdCode(prdCde);
            PrdInfoVO outputVo = prdInfoService.queryLastPrdInfo(vo);
            nlsCreditInfoVO.checkFor(new ValidatePrdRule(outputVo));
            String prdName = outputVo.getPrdName();
            boolean flag = ValidationUtils.validPhoneNum("0", mobile);// 手机号
            if (!flag) {
                throw new BizException("手机号错误");
            }

            // 4.调用中台服务
            // 插入授信申请基本信息表
            nlsCreditInfoVO = new NlsCreditInfoVO();
            nlsCreditInfoVO.setLmtApplySeq(applSeq);// 流水号
            nlsCreditInfoVO.setCusName(cusName);// 姓名+
            nlsCreditInfoVO.setCertType(certType);// 证件类型
            nlsCreditInfoVO.setCertCode(certNo);// 证件号码
            //nlsCreditInfoVO.setLmtType(LmtType);//额度类型
            nlsCreditInfoVO.setCyclicFlg(outputVo.getCyclicWay());//是否循环
            nlsCreditInfoVO.setPrdId(outputVo.getPrdId());// 产品id
            nlsCreditInfoVO.setPrdCode(prdCde);// 产品代码
            nlsCreditInfoVO.setPrdName(prdName);// 产品名称

            nlsCreditInfoVO.setAssureMeansMain(BaseConstant.ASSURE_MEANS_00);// 担保方式
            //nlsCreditInfoVO.setRepaymentMode(StringUtil.isNullorBank(outputVo.getRepayWay()) ? "" : SDicMappingServer.getLocalSysDicVal(SDicServerConstant.REPAY_WAY, outputVo.getRepayWay())); //还款方式
            //nlsCreditInfoVO.setApplyRateY(AmtUtil.checkDecimalInfo(outputVo.getLoanIntRate(), oneHundred_100));// 申请执行年利率
            nlsCreditInfoVO.setIsCreInfo(BaseConstant.YES);//是否同意查征信
            nlsCreditInfoVO.setCurrencyType(CurrencyConstant.CNY);// 币种

            nlsCreditInfoVO.setChannelNo(chanNo);// 渠道编号
            nlsCreditInfoVO.setIndivMobile(mobile);// 手机号码
            //nlsCreditInfoVO.setNational(StringUtil.isNullorBank(reqCreditBean.getNation()) ? CountryConstant.CHN : SDicMappingServer.getLocalSysDicVal(SDicServerConstant.COUNTRY, reqCreditBean.getNation()));// 国籍
            // 反洗钱增加字段 2019-07-01
            // 学历
            nlsCreditInfoVO.setEdu(reqCreditBean.getEduCd());
            // 职业
            nlsCreditInfoVO.setProfession(reqCreditBean.getCrr() == null ? ""
                    : SDicMappingServer.getLocalSysDicVal(SDicServerConstant.CRR, reqCreditBean.getCrr()));// 职业

            // 单位地址
            nlsCreditInfoVO.setWrkCorpAddr(reqCreditBean.getCorpAddr());
            // 职称
            nlsCreditInfoVO.setTtl(reqCreditBean.getProfTtl());
            nlsCreditInfoVO.setIndivComJobTtl(reqCreditBean.getPosCd());//职务
            nlsCreditInfoVO.setIndivComFld(reqCreditBean.getUnitBlngIdy());//行业
            // 证件地址 （户籍地址）
            //nlsCreditInfoVO.setCertAddr(reqCreditBean.getCertAddr());
            // 居住地址  （联系地址）
            nlsCreditInfoVO.setIndivRsdAddr(reqCreditBean.getRsdcAddr());
            nlsCreditInfoVO.setGender(reqCreditBean.getGnd());//性别
            nlsCreditInfoVO.setCertEndDt(reqCreditBean.getIdentMtrDt());//证件到期日
            nlsCreditInfoVO.setNational(reqCreditBean.getNation());//国籍
            nlsCreditInfoVO.setMrgSitu(reqCreditBean.getMrtlSitu());//婚姻状况

            nlsCreditInfoVO.setCreateUser(BaseConstant.ADMIN);// 创建人（直接插值）
            nlsCreditInfoVO.setCreateTime(DateUtility.getCurrAppDateTimeString());// 创建时间
            nlsCreditInfoVO.setApplyDate(DateUtility.getCurrDate());// 申请日期
            nlsCreditInfoVO.setApprvSts(MsLoanConstant.NlsApplyStateEnum.APPR.VALUE);// 处理中
            nlsCreditInfoVO.setGlobalSerno(glblSrlNo);// 全局流水号
            //期限
            nlsCreditInfoVO.setApplyTerm(outputVo.getCreditTerm());
            // 期限类型
            nlsCreditInfoVO.setTermType(outputVo.getCreditTermUnit());
            nlsCreditInfoVO.setEmergencyContactName(reqCreditBean.getUrgnCrsp());//联系人姓名
            nlsCreditInfoVO.setEmergencyContactRelate(reqCreditBean.getUrgnCrspRela());//联系人关系
            nlsCreditInfoVO.setEmergencyContactPhone(reqCreditBean.getUrgnCrspMblNo());//联系人手机号
            nlsCreditInfoVO.setReferrerId(reqCreditBean.getRefrId());//推荐人工号
            nlsCreditInfoVO.setCity(reqCreditBean.getCustAppWrbtCity());//客户申请所在城市
            nlsCreditInfoVO.setApprvDate(DateUtility.getCurrDate());// 审批日期
            nlsCreditInfoVO.setPostCode(reqCreditBean.getFamPstcd());
            nlsCreditInfoVO.setPlatfmid(
                    "".equals(esbReqServiceBean.getSysHead().getPlafmID()) || esbReqServiceBean.getSysHead().getPlafmID() == null ?
                            MsLoanConstant.PlafmEnum.YED.VALUE : esbReqServiceBean.getSysHead().getPlafmID()
            );// 平台ID
            nlsCreditInfoVO.setPlatfmusrid(
                    "".equals(esbReqServiceBean.getSysHead().getPlafmUsrID()) || esbReqServiceBean.getSysHead().getPlafmUsrID() == null ?
                            chanNo + certNo : esbReqServiceBean.getSysHead().getPlafmUsrID()
            );// 平台用户ID*/


            nlsCreditInfoVO.setSoltStage(PrdAdaptedSoltEnums.SoltStageEnum.CREDIT.getVALUE());//插槽阶段，授信
            // add by ludayong 2019/11/15 【数据权限】增加网贷经办机构赋值
            int num1 = nlsCreditInfoService.insertNlsCreditInfo(nlsCreditInfoVO);
            //异步送风控大屏展示-授信申请每一笔都要发送数据过去
            sendToRisk(nlsCreditInfoVO);
            // 插入网贷业务过程表
            NlsProcessBizVO inNlsProcessBizVo = new NlsProcessBizVO();
            inNlsProcessBizVo.setApplySeq(applSeq);// 申请流水号
            //inNlsProcessBizVo.setCusId(cusId);// 客户编号
            inNlsProcessBizVo.setCusName(cusName);// 客户名称
            inNlsProcessBizVo.setPrdId(outputVo.getPrdId());// 产品ID
            inNlsProcessBizVo.setPrdCode(prdCde);// 产品代码
            inNlsProcessBizVo.setPrdName(prdName);// 产品名称
            inNlsProcessBizVo.setHangTimes(QueueTaskEnums.QueueHangTimesEnum.INITIALIZE.getTimes());
            inNlsProcessBizVo.setQueueTaskState(QueueTaskEnums.QueueTaskStateEnum.EXECUTORY.getCode());
            inNlsProcessBizVo.setCreateTime(DateUtility.getCurrAppDateTimeString());// 创建时间
            inNlsProcessBizVo.setLastModifyTime(DateUtility.getCurrAppDateTimeString());// 最后修改时间
            inNlsProcessBizVo.setCreateDate(DateUtility.getCurrAppDateStr());// 创建日期
            // add by ludayong 2019/11/15 【数据权限】增加经办机构赋值
            // 经办机构
            inNlsProcessBizVo.setNlsOperOrgid(InstitutionEnums.InstitutionEnum.GZYHZHYHZXSCTD1.getCode());
            int num2 = nlsProcessBizService.insertNlsProcessBiz(inNlsProcessBizVo);
            //签章记录表插入数据 add by zhangxican
            int num3 = insertSqsRecord(reqCreditBean);
            //落客户信息拓展表
            NlsCreditInfoExdVO pojo=new NlsCreditInfoExdVO();
            pojo.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
            pojo.setCertType(certType);
            pojo.setCertCode(certNo);
            pojo.setEmergencyContactName(reqCreditBean.getUrgnCrsp());
            pojo.setEmergencyContactRelate(SDicMappingServer.getLocalSysDicVal(SDicServerConstant.CONSTACTS_RELATION, reqCreditBean.getUrgnCrspRela()));
            pojo.setEmergencyContactPhone(reqCreditBean.getUrgnCrspMblNo());
            pojo.setCreateTime(DateUtility.getCurrAppDateTimeString());
            pojo.setCreateUser(BaseConstant.ADMIN);
            pojo.setLastUpdateTime(DateUtility.getCurrAppDateTimeString());
            pojo.setLastUpdateUser(BaseConstant.ADMIN);
            pojo.setIndivDgr(reqCreditBean.getDgrCd());
            pojo.setIndivRsdSt(reqCreditBean.getRsdcSitu());
            int num4 = nlsCreditInfoExdService.insert(pojo);

            if (num1 == -1 || num2 == -1 || num3 == -1 || num4==-1) {
                throw new BizException("插入数据表异常!");
            }

            //异步调用白名单补录
            callSyncCompanyWhite(nlsCreditInfoVO);
                return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                        JSON.toJSONString(buildRespCreditBean(EsbBizEnums.YedRespCode.DISPOSING.getValue())),
                        EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                        EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                        "交易成功");
        } catch (ESBException e) {
            logger.error("授信申请服务接口处理失败!" + e.getMessage());
            e.printStackTrace();
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSON.toJSONString(buildRespCreditBean(EsbBizEnums.YedRespCode.REJECT.getValue())),
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                    EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(),
                    e.getMessage());
        } catch (BizException e) {
            logger.error("授信申请服务接口处理失败!" + e.getMessage());
            e.printStackTrace();
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSON.toJSONString(buildRespCreditBean(EsbBizEnums.YedRespCode.REJECT.getValue())),
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                    EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(),
                    e.getMessage());
        } catch (Exception e) {
            logger.error("授信申请服务接口处理失败!" + e.getMessage());
            e.printStackTrace();
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSON.toJSONString(buildRespCreditBean(EsbBizEnums.YedRespCode.REJECT.getValue())),
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                    EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(),
                    e.getMessage());
        } finally {
            logger.info("授信申请交易结束----------申请流水号：" + applSeq + "------------全局流水号" + glblSrlNo);
            TraceUtil.clear();
        }
    }

    private void sendToRisk(NlsCreditInfoVO nlsCreditInfoVO) {
        // 授信申请流水号
        String applySeq = nlsCreditInfoVO.getLmtApplySeq();
        logger.info("优e贷授信，发送kafka消息给大数据开始执行,流水号:" + applySeq);
        try {
            boolean flag = false;
            //查询开关
            List<NlsStageInfoVO> infoVOS = nlsStageInfoService.queryList();
            for(NlsStageInfoVO vo:infoVOS){
                if(vo.getPrdId().equals("11110004") && vo.getStatus().equals("on") && vo.getStage().equals("credit")){
                    flag = true;
                }
            }
            JSONObject jsonObject = new JSONObject();
            NlsCreditInfoNoticeVO array = new NlsCreditInfoNoticeVO();
            array.setTableName("NLS_CREDIT_INFO");
            //数据日期
            String timeStamp = TimeUtil.getTimeStampByPattern("yyyy-MM-dd HH:mm:ss");
            array.setApplyDate(timeStamp);
            array.setApproveAmt(nlsCreditInfoVO.getApproveAmt());
            array.setApprvDate(nlsCreditInfoVO.getApprvDate());
            array.setApprvSts(nlsCreditInfoVO.getApprvSts());
            array.setCertType(nlsCreditInfoVO.getCertType());
            array.setCertCode(nlsCreditInfoVO.getCertCode());
            array.setCertEndDt(nlsCreditInfoVO.getCertEndDt());
            array.setCusName(nlsCreditInfoVO.getCusName());
            array.setEdu(nlsCreditInfoVO.getEdu());
            array.setGender(nlsCreditInfoVO.getGender());
            array.setIndivRsdAddr(nlsCreditInfoVO.getIndivRsdAddr());
            array.setIndivComFld(nlsCreditInfoVO.getIndivComFld());
            array.setIndivMobile(nlsCreditInfoVO.getIndivMobile());
            array.setIndivComJobTtl(nlsCreditInfoVO.getIndivComJobTtl());
            array.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
            array.setMrgSitu(nlsCreditInfoVO.getMrgSitu());
            array.setNational(nlsCreditInfoVO.getNational());
            array.setProfession(nlsCreditInfoVO.getProfession());
            array.setRefuseCause(nlsCreditInfoVO.getRefuseCause());
            array.setWrkCorpAddr(nlsCreditInfoVO.getWrkCorpAddr());
            array.setWrkCorpNm(nlsCreditInfoVO.getWrkCorpNm());
            array.setDataTime(timeStamp);

            KafkaNoticeHeader header = new KafkaNoticeHeader();
            header.setMessageCode("YED_JISHI");
            header.setTimestamp(timeStamp);
            header.setTransactionId(getTransactionId());
            header.setSysName("netLoan");

            jsonObject.put("head", header);
            jsonObject.put("biz", array);

            if(!flag){
                logger.info("实时采集开关未打开！！！");
                return;
            }
            threadPool.add(() -> {
                KafkaUtil kafkaUtil = new KafkaUtil(kafkaServers, kafkaToptic);
                try {
                    kafkaUtil.sendMessage(JSONObject.toJSONString(jsonObject));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("优e贷授信，发送kafka消息给大数据失败，流水号：" + applySeq + ",异常信息：" + e.getMessage());
                }
            });
        } catch (Exception e) {
            logger.info("优e贷授信，发送kafka消息给大数据异常，流水号：" + applySeq + ",异常信息：" + e.getMessage());
        } finally {
            logger.info("优e贷授信，发送kafka消息给大数据结束，申请流水号：" + applySeq);
        }
    }

    public static String getTransactionId() {
        String transactionId = "SEQ" + DateFormatUtils.format(new Date(), DateFormatConstant.DATETIME_FORMAT_COMPACT, Locale.CHINA) +
                RandomCodeUtils.generateLetter(6);
        return transactionId;
    }
    /**
     * 组织用户借款请求接口的返回对象
     *
     * @param retCd 返回状态码
     * @return
     * @author huangwb
     * @version 1.0
     * @since 2019年1月20日 下午1:59:46
     */
    private RespYedCreditBean buildRespCreditBean(String retCd) {
        RespYedCreditBean respCreditBean = new RespYedCreditBean();
        respCreditBean.setRetStCd(retCd);
        return respCreditBean;
    }

    private void callSyncCompanyWhite(NlsCreditInfoVO nlsCreditInfoVO){
        try{
            threadPool.add(() -> {
                companyWhiteListRecordService.saveCompanyWhiteList(nlsCreditInfoVO);
            });
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }



    private int insertSqsRecord(ReqYEDCreditBean reqYEDCreditBean) {
        SignatureRecordVO signatureRecordVO = new SignatureRecordVO();
        signatureRecordVO.setId(UUIDUtil.getUUID());
        signatureRecordVO.setPrdId(YedConstantSet.prdId);
        signatureRecordVO.setApplySeq(reqYEDCreditBean.getCrAppSrlNo());
        signatureRecordVO.setLinkType(1);
        signatureRecordVO.setPolFileType(YedConstantSet.YED_FILE_TYPE_03);
        signatureRecordVO.setRetryNum(0);
        signatureRecordVO.setCreateTime(new Date());
        signatureRecordVO.setLastUpdateTime(new Date());
        signatureRecordVO.setSiuSta(0);
        return yedSqsSignatureService.insertRecord(signatureRecordVO);
    }




}
